package pers.jg.rrsserver.controller

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.google.gson.GsonBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import pers.jg.rrsserver.entity.ConsultQ
import pers.jg.rrsserver.mapper.ConsultQMapper

@RestController
@CrossOrigin
class ConsultQController {

    val dateFormat = "yyyy-MM-dd'T'HH:mm:sssZ"

    class ConsultQList {
        lateinit var consultQ: ArrayList<ConsultQ>
    }

    @Autowired
    private lateinit var consultQMapper: ConsultQMapper

    @PostMapping("/api/postNewQuestion")
    fun postNewQuestion(
        @RequestBody data: String
    ): String {

        val gson = GsonBuilder()
            .setDateFormat(dateFormat)
            .create()
        val question = gson.fromJson(data, ConsultQ::class.java)
        println(question.id)
        val res = consultQMapper.insert(question)
        return res.toString()

    }

    @GetMapping("/api/getQuestionList")
    fun getQuestionList(
        @RequestParam(value = "key", defaultValue = "") key: String,
        @RequestParam(value = "orderBy", defaultValue = "") orderBy: String,
        @RequestParam(value = "isIncludeOwn", defaultValue = "true") isIncludeOwn: Boolean,
        @RequestParam(value = "userId", defaultValue = "0") userId: Int
    ): String {
        val queryWrapper = QueryWrapper<ConsultQ>()
        if (key != "") {
            queryWrapper.like("title", key).or().like("content", key)
        }
        if (orderBy == "") {
            queryWrapper.orderByDesc("date")   // 按照时间降序排序
        } else {
            queryWrapper.orderByDesc(orderBy)   // 按照给定的字段降序排序
        }
        if (!isIncludeOwn) {
            queryWrapper.ne("user", userId)
        }
        val questionList = consultQMapper.selectList(queryWrapper)
        val gson = GsonBuilder()
            .create()
        return gson.toJson(questionList)
    }


    @PostMapping("/api/updateQuestion")
    fun updateQuestion(
        @RequestBody data: String
    ): String {

        val gson = GsonBuilder()
            .setDateFormat(dateFormat)
            .create()
        val question = gson.fromJson(data, ConsultQ::class.java)
        println(question.id)
        val res = consultQMapper.updateById(question)
        return res.toString()
    }

    @PostMapping("/api/deleteQuestion")
    fun deleteQuestion(
        @RequestParam("id") id: String
    ): String {
        println(id)
        return consultQMapper.deleteById(id).toString()
    }

    @GetMapping("/api/getQuestion")
    fun getQuestion(
        @RequestParam("id") id: String
    ): String {
        val question = consultQMapper.selectById(id)
        val gson = GsonBuilder()
            .create()
        return gson.toJson(question)
    }

}